package myauctioneer;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.lang.reflect.Method;

import org.stringtemplate.v4.ST;

public class DefaultServlet extends HttpServlet
{
	/**
	 * Reference to the context-wide global App object.
	 */
	protected App app = null;

	public void init() throws ServletException
	{
		if(this.app == null)
			this.app = (App) this.getServletContext().getAttribute("app");

		if(this.app == null) {
			try {
				this.app = new App(
					this.getServletContext().getRealPath("/"), // baseDir
					this.getServletContext().getContextPath() // baseUrl
				);
			}
			catch(Exception e) {
				throw new ServletException(e.toString(), e);
			}

			this.getServletContext().setAttribute("app", this.app);
		}
	}

	/**
	 * Parse action name from request.
	 *
	 * @param request The servlet request currentry processing
	 */
	protected void parseRequest(HttpServletRequest request)
	{
		String[] parts = request.getPathInfo() == null
			? new String[0]
			: request.getPathInfo().split("/");

		String action = "";

		/**
		 * Check action name
		 */
		if(parts.length > 1)
			action = parts[1];

		if(action.isEmpty())
			action = "index";

		request.setAttribute("action", action);
	}

	/**
	 * Respond to a request for the content produced by
	 * this servlet.
	 *
	 * @param request The servlet request we are processing
	 * @param response The servlet response we are producing
	 *
	 * @exception IOException if an input/output error occurs
	 * @exception ServletException if a servlet error occurs
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		response.setContentType("text/html; charset=utf-8");

		this.parseRequest(request);

		Method actionMethod = null;
		String action = (String) request.getAttribute("action");

		try {
			actionMethod = this.getClass().getDeclaredMethod(
				action + "Action",
				HttpServletRequest.class,
				HttpServletResponse.class
			);
		}
		catch(Exception e) { // NoSuchMethodException, SecurityException
			this.notFoundAction(request, response);
			return;
		}

		try {
			actionMethod.invoke(this, request, response);
			//response.getWriter().println(actionMethod.toString());
		}
		//catch (IllegalAccessException iae) {
		//	throw new ServletException("IAE: " + iae.toString() + " (" + obj.toString() + ")");
		//}
		//catch(java.lang.reflect.InvocationTargetException ite) {
		//	throw new ServletException("ITE: " + ite.toString() + " (" + obj.toString() + ")");
		//}
		catch(Exception e) {
			throw new ServletException("E: " + e.toString(), e);
		}
	}

	/**
	 * Not found (404) action method.
	 */
	public void notFoundAction(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		response.setStatus(404);

		ST rootTpl = this.app.getTemplate("root");
//CHANGE TO DEDICATED FUNCTION ... START		
		/**
		 * Check if logged in as customer,
		 * if YES, don't allow to create new customer
		 */
		Customer customer = new Customer(this.app);
		customer.load(request.getSession());

		boolean isLoggedIn=false;
		try {
			isLoggedIn=customer.isLoggedIn(request.getSession());
		}
		catch (Exception e /*ServletException se*/) {
			rootTpl.add("msg", e.toString());
		}
		if (!isLoggedIn) rootTpl.add("login","");	
//CHANGE TO DEDICATED FUNCTION ... END

		ST tpl = this.app.getTemplate("notfound");

		tpl.add("request", request);

		rootTpl.add("title", "Page not found (DefaultServlet)");
		rootTpl.add("content", tpl);

		response.getWriter().println(rootTpl.render());
	}

	/**
	 * Index action method.
	 */
	public void indexAction(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException
	{
		ST rootTpl = this.app.getTemplate("root");
//CHANGE TO DEDICATED FUNCTION ... START		
		/**
		 * Check if logged in as customer,
		 * if YES, don't allow to create new customer
		 */
		Customer customer = new Customer(this.app);
		customer.load(request.getSession());

		boolean isLoggedIn=false;
		try {
			isLoggedIn=customer.isLoggedIn(request.getSession());
		}
		catch (Exception e /*ServletException se*/) {
			rootTpl.add("msg", e.toString());
		}
		if (!isLoggedIn) rootTpl.add("login","");			
//CHANGE TO DEDICATED FUNCTION ... END		
		ST homeTpl = this.app.getTemplate("home");
		
		//db
		
		

		rootTpl.add("title", "Application Test (DefaultServlet)");
		rootTpl.add("content", homeTpl);

		response.getWriter().println(rootTpl.render());
	}
}
